package com.dcxt.config;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class Config {
	private SQLiteDatabase zwdb;
	private String dbName = "zwdc.db";
	private static Context ctxt;
	private static Config config;

	public static void setCtxt(Context ctxt) {
		synchronized (Config.class) {
			if (Config.ctxt == null)
				Config.ctxt = ctxt;
		}
	}

	public static Config getInstance() {
		if (ctxt == null)
			throw new IllegalStateException("please set context!");
		synchronized (Config.class) {
			if (config == null)
				config = new Config();
			return config;
		}
	}

	private Config() {
		init();
	}

	private void init() {
		zwdb = ctxt.openOrCreateDatabase(dbName, ctxt.MODE_PRIVATE, null);
		try {
			zwdb.execSQL("CREATE TABLE ZW_PARAM(paramName varchar(15),paramValue varchar(100));");
		} catch (Exception e) {
		}
		zwdb.close();
	}

	public String getProperty(String name) {
		String value = null;
		try {
			zwdb = ctxt.openOrCreateDatabase(dbName, ctxt.MODE_PRIVATE, null);
			Cursor cur = zwdb.rawQuery(
					"SELECT * FROM ZW_PARAM WHERE paramName=?",
					new String[] { name });
			if (cur != null) {
				int columnIndex = cur.getColumnIndex("paramValue");
				if (cur.moveToFirst()) {
					value = cur.getString(columnIndex);
				}
			}
		} catch (Exception e) {
		} finally {
			if (zwdb != null) {
				zwdb.close();
			}
		}
		return value;
	}

	public void saveProperty(String name, String value) {
		try {
			zwdb = ctxt.openOrCreateDatabase(dbName, ctxt.MODE_PRIVATE, null);
			Cursor cur = zwdb.rawQuery(
					"SELECT * FROM ZW_PARAM WHERE paramName=?",
					new String[] { name });
			boolean exists = false;
			if (cur != null) {
				if (cur.moveToFirst()) {
					exists = true;
				}
			}
			String sql = null;
			if (exists) {
				sql = "UPDATE ZW_PARAM SET paramValue='" + value
						+ "' WHERE paramName = '" + name + "'";
			} else {
				sql = "INSERT INTO ZW_PARAM(paramName,paramValue) VALUES('"
						+ name + "','" + value + "')";
			}
			zwdb.execSQL(sql);
		} finally {
			if (zwdb != null)
				zwdb.close();
		}

	}
}
